CryptoJS AES加密 发表于 2020-03-10 | 更新于 2020-09-25 | 分类于 JavaScript | 评论数: | 阅读次数: 使用CryptoJS加解密敏感数据 加密模式:AES-128-CBC1234567891011121314151617181920212223242526272829303132// 服务端提供密钥与偏移量// 'key' => '0123456789abcdef'// 'iv' => 'abcdef0123456789'import CryptoJS from 'crypto-js'const AES_KEY = '0123456789abcdef' // 密钥, AES-128 需16个字符, AES-256 需要32个字符const AES_IV = 'abcdef0123456789' // 密钥偏移量,16个字符const key = CryptoJS.enc.Utf8.parse(AES_KEY)const iv = CryptoJS.enc.Utf8.parse(AES_IV)// 加密export function encrypt(data) { const srcs = CryptoJS.enc.Utf8.parse(data) const encrypted = CryptoJS.AES.encrypt(srcs, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }) return encrypted.toString()}// 解密export function decrypt(data) { const decrypted = CryptoJS.AES.decrypt(data, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }) return CryptoJS.enc.Utf8.stringify(decrypted).toString()} 12345encrypt('test')// 'cExA749M38c0L1J3HY6WTA=='decrypt('cExA749M38c0L1J3HY6WTA==')// test